package com.ddshuai.easy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * 描述 新通教育
 * 给定一个二叉树，返回其节点值自底向上的层次遍历。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 *
 * @author ddshuai
 * @date 2018-12-14 16:14
 **/
public class LevelOrderBottom {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.empty()) {

            List<Integer> list = new ArrayList<>();
            List<TreeNode> treeNodes = new ArrayList<>();
            while (!stack.empty()) {
                TreeNode treeNode = stack.pop();
                list.add(treeNode.val);

                if (treeNode.left != null) {
                    treeNodes.add(treeNode.left);
                    // temp.push(treeNode.left);
                }

                if (treeNode.right != null) {
                    treeNodes.add(treeNode.right);
                    // temp.push(treeNode.right);
                }
            }
            Collections.reverse(treeNodes);
            for (TreeNode treeNode : treeNodes) {
                stack.push(treeNode);
            }
            lists.add(list);
        }
        Collections.reverse(lists);
        return lists;
    }



    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
